<template>
<div class="chatContainer">
  <div class="leftBox">
    <ul>
      <li :class="{choose:chooseIndex === index}" @click="changeUser(item.chatId,item.chatname,index)" class="userList" v-for="(item,index) in chatUserList" :key="item.chatId">
        <img :src="item.avatarUrl" alt="">
        <div class="chatUserInfo">
          <span>{{item.chatname}}</span>
        </div>
      </li>
    </ul>
  </div>
  <div class="rightBox">
    <div class="title">与{{toUserName}}的对话</div>
    <div class="chatContent" id="chatRecord">
      <div class="chatItem" v-for="(item,index) in chatList" :key="index">
        <div v-if="item.from_id!=userId" style="display:flex;flex-direction:column;align-items:flex-start;">
          <div style="display:flex;align-items:center;">
            <img :src="item.avatarUrl" alt="">
            <i class="iconfont icon-shixiangzuojiantou-"></i>
            <div class="messageBox1">{{item.content}}</div>
          </div>
          <span class="otherTime">{{item.send_time}}</span>
        </div>
        <div v-else style="display:flex;flex-direction:column;align-items:flex-end;">
          <div style="display: flex;align-items: center;">
            <div class="messageBox2">{{item.content}}</div>
            <i class="iconfont icon-shixiangyoujiantou-"></i>
            <img :src="item.avatarUrl1" alt="">
          </div>
          <span class="myselfTime">{{item.send_time}}</span>
        </div>
      </div>
    </div>
    <div class="footerArea">
      <el-input placeholder="请输入聊天内容" type="textarea" v-model="textarea"></el-input>
      <el-button @click="sendMsg" type="primary">发送</el-button>
    </div>

  </div>
</div>
</template>

<script>
import formatTime from '../utils/formatTime'
export default {
  data () {
    return {
      chatList: [

      ],
      ws: {},
      toUserId: '',
      textarea: '',
      userId: '',
      chatUserList: [],
      toUserName: '',
      chooseIndex: 0
    }
  },
  methods: {
    ws_conect () {
      const id = JSON.parse(window.sessionStorage.getItem('userInfo')).id
      console.log(id)
      var ws = new WebSocket('ws://localhost:8181?id=' + id)
      this.ws = ws
      ws.onopen = function (e) {
        console.log('Connection to server opened')
      }
      ws.onmessage = this.ws_onmessage
      ws.onclose = this.ws_close
    },
    ws_onmessage (e) {
      console.log(e)
      var data = JSON.parse(e.data)
      if (data.code === 200) {
        this.online_list = data.online_user
      } else if (data.code === 202) {
        // eslint-disable-next-line eqeqeq
        if (data.from_id == this.toUserId) {
          this.chatList.push(data)
        }
      }
      console.log('我client收到消息了：' + e.data)
    },
    ws_close (e) {},
    async sendMsg () {
      if (this.textarea.trim() === '') {
        return this.$message.error('消息不能为空！')
      }
      let obj = {
        token: this.toUserId,
        name: this.toUserName,
        content: this.textarea,
        from_id: this.userId,
        send_time: formatTime(new Date(), 'YY-MM-DD HH:mm:ss')
      }
      this.ws.send(JSON.stringify(obj))
      var msg = {
        name: obj.token,
        content: this.textarea,
        from_id: this.userId,
        send_time: formatTime(new Date(), 'YY-MM-DD HH:mm:ss')
      }
      this.chatList.push(msg)
      await this.$http.post('/record/createRecord', {
        from: this.userId,
        to: this.toUserId,
        content: this.textarea,
        sendTime: Number(new Date())
      })
      this.textarea = ''
    },
    changeUser (id, name, index) {
      this.toUserId = id
      this.toUserName = name
      this.chooseIndex = index
      this.getRecordList()
    },
    async getRecordList () {
      const res = await this.$http.post('/record',
        {from: this.userId, to: this.toUserId}
      )
      this.chatList = res.data
      console.log(this.chatList, 'ooo')
      this.chatList.forEach(item => {
        item.send_time = formatTime(item.send_time, 'YY-MM-DD HH:mm:ss')
        item.avatarUrl = `http://localhost:8000/users/${item.from_id}/avatar`
        item.avatarUrl1 = `http://localhost:8000/users/${item.from_id}/avatar`
      })
    },
    async getChatUserList () {
      const res = await this.$http.get(`/userlist/${this.userId}`)
      this.chatUserList = res.data
      this.chatUserList.forEach(item => {
        item.avatarUrl = `http://localhost:8000/users/${item.chatId}/avatar`
      })
      console.log(this.chatUserList, 'opopop')
      // eslint-disable-next-line eqeqeq
      let i = this.chatUserList.findIndex((item) => item.chatId == this.toUserId)
      if (i !== -1) {
        this.chatUserList.splice(i, 1)
      }
      this.chatUserList.unshift({chatId: this.toUserId, chatname: this.toUserName, updateAt: Number(new Date())})
    }
  },
  created () {
    this.$store.commit('setChoose', 'chat')
    this.ws_conect()
    this.userId = JSON.parse(window.sessionStorage.getItem('userInfo')).id
    this.toUserId = this.$route.query.id
    this.toUserName = this.$route.query.name
    this.getRecordList()
    this.getChatUserList()
  },
  mounted () {
  },
  updated () {
    let ele = document.getElementById('chatRecord')
    ele.scrollTop = ele.scrollHeight
  }
}
</script>

<style scoped>
  .chatContainer{
    height: 100%;
    display: flex;
    background-color: cornsilk;
    padding: 30px 300px;
  }
  .leftBox{
    background-color: #fff;
    width: 260px;
    margin-right: 20px;
  }
  .rightBox{
    background-color: #fff;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .rightBox .title{
    text-align: center;
    height: 44px;
    line-height: 44px;
    background-color: #f7f8f9;
  }
  .chatContent{
    flex:1;
    overflow: auto;
    padding: 10px;
    border-bottom: 1px solid #888;
  }
  .chatItem{
    min-height: 72px;
    position: relative;
    margin: 20px 0;
  }
  .chatItem img{
    height: 40px;
    width: 40px;
    border-radius: 50%;
    margin: 0 10px;
  }
  .myself{
    position: absolute;
    right: 10px;
  }
  .userList{
    text-align: center;
    height: 40px;
    padding: 10px;
    background-color: #fff;
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .userList img{
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .rightBox .footerArea{
    height: 100px;
    display: flex;
    flex-direction: column;
    padding: 10px;
  }
  .rightBox .footerArea .el-button{
    align-self: flex-end;
    margin-top:5px;
  }
  .chatUserItem{
    display: flex;
    flex-direction: column;
  }
  .messageBox1{
    border-radius: 8px;
    position: relative;
    background: #ebf8f5;
    max-width: 537px;
    padding: 10px;
    text-align: left;
    color: #666;
  }
  .messageBox2{
    border-radius: 8px;
    position: relative;
    background: #ebf8f5;
    max-width: 537px;
    padding: 10px;
    text-align: left;
    color: #666;
  }
  .choose,.userList:hover{
    background-color: #f1f1f1;
  }
  .myselfTime{
    font-size: 12px;
    color: #999;
    margin-right: left;
    margin: 5px 0;
    margin-right: 80px;
  }
  .otherTime{
    font-size: 12px;
    color: #999;
    margin-right: auto;
    margin: 5px 0;
    margin-left: 80px;
  }
  .icon-shixiangzuojiantou-{
    font-size: 20px;
  }
  .icon-shixiangyoujiantou-{
    font-size:20px;
  }
  .chatUserInfo{
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
  }
  .chatUserInfo span{
    margin: 2px 0;
  }
</style>
